//  This product includes software developed by Denim Group, Ltd. (http://www.denimgroup.com/)
//  All use and distribution of the Denim Group developed software is subject to Version 2.0
//  of the Apache License (http://www.apache.org/licenses/LICENSE-2.0).

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AppScan;
using AppScan.Scan.Results;
using System.Runtime.InteropServices;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace AppScan.DefectLogger
{
	partial class LogDefectForm
	{
		private void LogBtn_Click(object sender, EventArgs e)
		{
			// Make sure we have a the minimal data
			if (string.IsNullOrEmpty(SubjectTB.Text) || string.IsNullOrEmpty(DescriptionTB.Text))
			{
				MessageBox.Show("The subject & Description must be filled");
				return;
			}

			IDefectTrackingSystem defectSystem;
			try
			{
				defectSystem = _extension.DefectTrackingSystem;
				defectSystem.Login(_extension.Config.ServerUrl, UserNameTB.Text, PasswordTB.Text, _extension.Config.DomainName, _extension.Config.ProjectName);
			}
			catch (Exception)
			{
				MessageBox.Show("Login failed.");
				return;
			}


			try
			{
                string selectedProject = _extension.Config.ProjectName;
                Project project = GetProjectFromString(selectedProject);

                WorkItem newBug = new WorkItem(GetItemType(project, "Bug"));

                newBug.Title = SubjectTB.Text;
                newBug.AreaPath = project.Name;
                newBug.Description = DescriptionTB.Text;
                //  TODO - Link up severity with actual severity of finding (must also match with available severities)
                newBug.Fields["Priority"].Value = 1;

                //  TODO - Clean up adding attachment files so that we can include
                //  a description of what the attached file i

                string[] attachedFileNames = AttachedFiles;
                foreach (string filename in attachedFileNames)
                {
                    Attachment attachment = new Attachment(filename, string.Empty);
                    newBug.Attachments.Add(attachment);
                }

                //  TODO - Possibly include custom fields

                //Check if values are valid
                if (!newBug.IsValid())
                {
                    ArrayList list = newBug.Validate();
                    StringBuilder sb = new StringBuilder();
                    sb.Append("Invalid fields for new Team Foundation Server work item: ");
                    foreach (Field f in list)
                    {
                        sb.Append("Field: " + f.Name + ", ");
                    }
                    MessageBox.Show("New issue is not valid: " + sb.ToString());
                }
                else
                {
                    newBug.Save();
                    MessageBox.Show("Successfully logged as defect " + newBug.Id);
                    Close();
                }
            }
			catch (Exception ex)
			{
				MessageBox.Show("Failed to log defect: " + ex.Message);
				return;
			}
		}

        public Project GetProjectFromString(string ProjectName)
        {
            TeamFoundationServer server = GetServer();
            server.Authenticate();
            WorkItemStore store = new WorkItemStore(server);
            return store.Projects[ProjectName];
        }

        public TeamFoundationServer GetServer()
        {
            IDefectTrackingSystem defectSystem;
            defectSystem = _extension.DefectTrackingSystem;
            TeamFoundationServer retVal = defectSystem.NativeConnection as TeamFoundationServer;
            return (retVal);
        }

        public WorkItemType GetItemType(Project project, String type)
        {
            return (project.WorkItemTypes[type]);
        }

		private void DoOnLoadUpdates()
		{
			return;
		}
	}
}
